import { createApp } from 'vue';
import MaplibPopup from './MaplibPopup.vue';
import mitt from 'mitt';

export function geomFirst(obj) {
  if (obj && obj.features && obj.features.length > 0) {
    return obj.features[0];
  }

  return null;
}

export async function tableData(obj, infoApi) {
  const gf = geomFirst(obj);
  if (gf) {
    if (gf.properties) {
      return await infoApi(gf.properties);
    }
  }

  return {};
}

export async function createPopUp(
  features,
  tableSchema,
  clickPopUpOk,
  infoApi,
  clickButtonOk,
  otherProps = {},
) {
  return createPopUpEx(
    features,
    tableSchema,
    clickPopUpOk,
    infoApi,
    clickButtonOk,
    null,
    null,
    null,
    otherProps,
  );
}

export async function createPopUpEx(
  features,
  tableSchema,
  clickPopUpOk,
  infoApi,
  clickButtonOk,
  clickButtonFire,
  clickButtonPolice,
  clickButtonZhujian,
  otherProps = {},
) {
  const obj = await tableData(features, infoApi);
  const theApp = createApp(MaplibPopup, {
    obj: obj,
    tableSchema: tableSchema,
    ...otherProps,
  });
  const node = document.createElement('div', {});
  const emitter = mitt();
  emitter.on('clickok', clickPopUpOk);
  if (clickButtonOk) {
    emitter.on('clickbutton', clickButtonOk);
  }
  if (clickButtonFire) {
    emitter.on('clickbuttonfire', clickButtonFire);
  }
  if (clickButtonPolice) {
    emitter.on('clickbuttonpolice', clickButtonPolice);
  }
  if (clickButtonZhujian) {
    emitter.on('clickbuttonzhujian', clickButtonZhujian);
  }
  theApp.provide('theMitt', emitter);
  const inst = theApp.mount(node);
  return inst.$el;
}
